/* eslint-disable react/jsx-key */
import React, { useRef, useState } from 'react';
import { Modal, Form, message, Tooltip } from 'antd';
import { connect, useRequest } from 'umi';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { postFetch } from '@/utils/doFetch';
import moment from 'moment';
import { doFetch } from '@/utils/doFetch';

import CompanyName from '@/components/CompanyName';
import { method } from 'lodash';

let Dossier = (props) => {
  const { global, dispatch } = props;
  let actionRef = useRef(),
    tableform = useRef(),
    ChildRef = null,
    [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState({}),
    [iftype, ciftype] = useState({}),
    [formRef] = Form.useForm();

  const [selectedRowKeys, setselectedRowKeys] = useState([]);

  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }

  const { run, loading } = useRequest(postFetch, {
    manual: true,
    formatResult: (res) => res,
    onSuccess: (result, params) => {
      message.destroy();
      if (result.code == 0) {
        message.success(result.message);
        actionRef.current.reload();
        cvs(false);
      } else {
        message.error(result.message);
      }
    },
  });

  const columns = [
    {
      title: '入库条码号',
      dataIndex: 'voucher_barcode',
      key: 'voucher_barcode',
    },
    {
      title: '存放位置',
      dataIndex: 'address',
      key: 'address',
      search: false,
      renderText: (text, row) => {
        return (
          <Tooltip title={text + row.rule_code} placement="topLeft">
            <span>{text + row.rule_code}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '公司名称',
      width: 260,
      dataIndex: 'company_name',
      key: 'company_name',
      render: (_, row) => (
        <CompanyName
          row={{ ...row, name: row?.company_name ?? row?.name, id: row?.company_id ?? row?.id }}
          reload={reload}
        />
      ),
    },
    {
      title: '凭证月份',
      dataIndex: 'voucher_date',
      key: 'voucher_date',
      valueType: 'dateMonth',
    },
    {
      title: '入库日期',
      dataIndex: 'submit_date',
      key: 'submit_date',
      valueType: 'date',
      render: (text, row) => {
        return (
          <span>{row.submit_date ? moment(row.submit_date).format('YYYY/MM/DD HH:mm') : '-'}</span>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'process_status_name',
      key: 'process_status_name',
      search: false,
    },
    {
      title: '记账会计',
      dataIndex: 'account_name',
      key: 'account_name',
    },
  ];

  let saveData = (values, fn) => {
    //  /wbn-api/voucher/lend_company

    //     PUT /wbn-api/voucher/batch_update_barcode
    // 参数：data（数组）

    // [
    //   { id: '凭证id', voucher_barcode: '凭证新的条码' },
    //   .....
    // ]
    if (values?.data?.length === 0) {
      return;
    }

    doFetch({
      url: '/wbn-api/voucher/batch_update_barcode',
      params: {
        data: values?.data?.map((it) => ({
          id: it.id,
          voucher_barcode: it?.voucher_barcodes ?? null,
        })),
      },
      method: 'PUT',
    }).then((res) => {
      if (res.code == 0) {
        message.success('操作成功');
        reload();
        cvs(false);
        setselectedRowKeys([]);
      }
    });
  };

  return (
    <div className="nopa autotable">
      <AutoTable
        formRef={tableform}
        pagetitle={props.route.name}
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path="/wbn-api/voucher/voucher_manage"
        rowSelection={{
          selectedRowKeys: selectedRowKeys?.map?.((it) => it?.id),
          preserveSelectedRowKeys: true,
          onChange: (selectedRowKeyes, selectedRows) => {
            setselectedRowKeys(selectedRows);
          },
        }}
        pageextra={
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <a
              disabled={selectedRowKeys.length == 0}
              style={{ marginRight: 12 }}
              onClick={() => {
                if (selectedRowKeys.length == 0) {
                  return;
                }
                ciftype({
                  val: 'bro',
                  title: '批量修改',
                });

                cf(() => {
                  return {
                    data: {
                      value: null,
                      type: 'table',
                      title: '批量修改凭证编号',
                      name: ['data'],
                      required: false,
                      pagination: false,
                      col: { span: 24 },
                      rowKey: 'id',
                      rowName: 'voucher_barcode',
                      value: selectedRowKeys,
                      columns: [
                        {
                          title: '入库条码号',
                          dataIndex: 'voucher_barcode',
                          key: 'voucher_barcode',
                          editable: false,
                        },
                        {
                          title: '修改-凭证条码号',
                          dataIndex: 'voucher_barcodes',
                          key: 'voucher_barcodes',
                        },
                        {
                          title: '存放位置',
                          dataIndex: 'address',
                          key: 'address',
                          search: false,
                          editable: false,
                          render: (text, row) => {
                            return (
                              <Tooltip title={text + row.rule_code} placement="topLeft">
                                <span>{text + row.rule_code}</span>
                              </Tooltip>
                            );
                          },
                        },
                        {
                          title: '公司名称',
                          width: 260,
                          dataIndex: 'company_name',
                          key: 'company_name',
                          editable: false,
                          render: (_, row) => (
                            <CompanyName
                              row={{
                                ...row,
                                name: row?.company_name ?? row?.name,
                                id: row?.company_id ?? row?.id,
                              }}
                              reload={reload}
                            />
                          ),
                        },
                        {
                          title: '凭证月份',
                          dataIndex: 'voucher_date',
                          key: 'voucher_date',
                          valueType: 'dateMonth',
                          editable: false,
                        },
                        {
                          title: '入库日期',
                          dataIndex: 'submit_date',
                          key: 'submit_date',
                          valueType: 'date',
                          editable: false,
                          render: (text, row) => {
                            return (
                              <span>
                                {row.submit_date
                                  ? moment(row.submit_date).format('YYYY/MM/DD HH:mm')
                                  : '-'}
                              </span>
                            );
                          },
                        },
                        {
                          title: '状态',
                          dataIndex: 'process_status_name',
                          key: 'process_status_name',
                          search: false,
                          editable: false,
                        },
                        {
                          title: '记账会计',
                          dataIndex: 'account_name',
                          key: 'account_name',
                          editable: false,
                        },
                      ],
                      maxLength: selectedRowKeys.length,
                    },
                  };
                });
                cvs(true);
              }}
            >
              批量修改
            </a>
          </div>
        }
        extraparams={{
          is_service: 1
        }}
      />

      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        destroyOnClose={true}
        width={1366}
      >
        <InitForm
          formRef={formRef}
          fields={fields}
          submitData={(values, fn) => {
            saveData(values, fn);
          }}
          onChange={(changedValues, allValues) => { }}
          submitting={loading || !vs}
          halfsave={false}
        />
      </Modal>
    </div>
  );
};

export default connect(({ global, loading }) => ({
  global,
  loading,
}))(Dossier);
